package com.firstclass.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.ArrayList;
import java.util.List;

/**
 * json 工具类
 */
public class FastJsonUtils {
    private FastJsonUtils() {}

    public static <T> T parseObject(String data, Class<T> clazz) {
        return JSONObject.parseObject(data, clazz);
    }

    public static <T> T parseObject(String data, String target, Class<T> clazz) {
        JSONObject jsonData = (JSONObject) JSONObject.parse(data);
        return parseObject(jsonData, target, clazz);
    }

    public static <T> T parseObject(JSONObject jsonObject, String target, Class<T> clazz) {
        if (jsonObject != null) {
            return jsonObject.getObject(target, clazz);
        }
        return null;
    }

    public static <T> List<T> parseArray(JSONObject jsonObject, String target) {
        JSONArray jsonArray = (JSONArray) jsonObject.get(target);
        List<T> res = new ArrayList<>();
        for (Object o : jsonArray) {
            res.add((T) o);
        }
        return res;
    }

    public static <T> List<T> parseArray(String json, String target) {
        JSONObject jsonData = (JSONObject) JSONObject.parse(json);
        return parseArray(jsonData, target);
    }

    public static String objectToJson(Object source) {
        return JSON.toJSONStringWithDateFormat(source, "yyyy-MM-dd HH:mm:ss",
                SerializerFeature.WriteDateUseDateFormat);
    }

}
